<template>
  <div>
    <el-button type="primary" size="small" @click="open(null)">新增</el-button>

    <el-button type="primary" size="small" @click="BatchBut">批删</el-button>

    <el-table
      ref="multipleTableRef"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" :selectable="selectable" />
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column prop="shoopsName" label="商品名称" width="100" />
      <el-table-column prop="batchId" label="生产批次" width="100" />
      <el-table-column prop="shelflife" label="保质期" width="100" />
      <el-table-column
        prop="productionnumber"
        label="生产许可证号"
        width="160"
      />
      <el-table-column prop="manufacturers" label="生产企业" width="120" />
      <el-table-column prop="createName" label="创建人" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="120">
        <template #default="scope">
          {{
            scope.row.createTime ? scope.row.createTime.substring(0, 10) : " "
          }}
        </template>
      </el-table-column>
      <el-table-column prop="updateName" label="修改人" width="120" />
      <el-table-column prop="updateTime" label="修改时间" width="120">
        <template #default="scope">
          {{
            scope.row.updateTime ? scope.row.updateTime.substring(0, 10) : " "
          }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="300">
        <template #default="scope">
          <el-button type="primary" size="small" @click="open(scope.row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="DelProducts(scope.row.productsId)"
            >删除</el-button>
              <el-button
            type="primary"
            size="small"
            @click="getFarmsInfo(scope.row.batchId)"
            >溯源详情</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <div>
    <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 新增 -->
  <div>
    <el-dialog
      v-model="dialog.dialogFormVisible"
      :title="dialog.title"
      width="500"
    >
      <el-form :model="form">
        <el-form-item label="商品名称:" :label-width="formLabelWidth">
          <el-select v-model="form.shoopId">
            <el-option label="请选择" :value="0"></el-option>
            <el-option
              v-for="item in shoops"
              :label="item.shoopsName"
              :value="item.shoopsId"
            />
          </el-select>
        </el-form-item>
           <el-form-item label="生产批次:" :label-width="formLabelWidth">
          <el-input v-model="form.batchId" autocomplete="off" />
        </el-form-item>
        <el-form-item label="保质期(天):" :label-width="formLabelWidth">
          <el-input v-model="form.shelflife" autocomplete="off" />
        </el-form-item>
        <el-form-item label="生产企业:" :label-width="formLabelWidth">
          <el-input v-model="form.manufacturers" autocomplete="off" />
        </el-form-item>
        <!-- <el-form-item label="封面图:" :label-width="formLabelWidth">
        </el-form-item> -->
        <el-form-item label="封面图" prop="productsimg">
          <el-input v-model="form.productsimg" />
          <el-upload
            class="avatar-uploader"
            action="http://localhost:5004/api/UpLoad/UploadImages"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="form.productsimg"
              :src="form.productsimg"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="CreateProducts()"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElTable, ElMessageBox } from "element-plus";
import axios from "axios";
import { useRouter } from "vue-router";
import { useCounterStore } from "@/stores/counter";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import type { TableInstance } from "element-plus";

const multipleTableRef = ref<TableInstance>();
const multipleSelection = ref<any[]>([]);
const store = useCounterStore();

const router = useRouter();
const tableData = ref([]);

const page = ref({
  totalCount: 0,
  totalPage: 0,
  PageIndex: 1,
  PageSize: 15,
  ShoopsName: "",
});
onMounted(() => {
  getProductsShoop();
  getShoops();
});

//显示生产信息
const getProductsShoop = () => {
  axios
    .get("http://localhost:5103/api/Traceability/GetProductsShoop", {
      params: page.value,
    })
    .then((res) => {
      tableData.value = res.data.data;
      page.value.totalCount = res.data.totalCount;
      page.value.totalPage = res.data.totalPage;
    });
};

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  page.value.PageSize = val;
  getProductsShoop();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  page.value.PageIndex = val;
  getProductsShoop();
};

//#region
const dialogTableVisible = ref(false);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

const dialog = reactive({
  dialogFormVisible: false,
  title: "",
  IsAdd: true,
});
const form = reactive({
  productsId: 0,
  shoopId: 0,
  batchId: 0,
  shelflife: 0,
  productionnumber: "",
  manufacturers: "",
  productsimg: "",
  createName: store.ccstore.userName,
  createTime: new Date(),
  updateName: "",
  updateTime: new Date(),
  isDel: true,
});

const shoops = ref([]);

const getShoops = () => {
  axios.get("http://localhost:5103/api/Traceability/QueryShoop").then((res) => {
    console.log(res.data);
    shoops.value = res.data.data;
  });
};

import { useRoute } from "vue-router";
const route = useRoute();
const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
      imageUrl.value = URL.createObjectURL(uploadFile.raw!)
console.log( imageUrl.value )
    form.productsimg =  imageUrl.value ;
    form.productsimg =  response ;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片类型必须为 JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 保存
const CreateProducts = () => {
  /*  if (form.batchId == 0) {
    ElMessage.error("请选择商品名称");
    return;
  } */
  if (form.shelflife == 0) {
    ElMessage.error("请选择保质期");
    return;
  }
  if (form.manufacturers == "") {
    ElMessage.error("请输入生产企业");
    return;
  }
  if (form.productsimg == "") {
    ElMessage.error("请上传产品图片");
    return;
  }

  if (dialog.IsAdd) {
    axios
      .post("http://localhost:5004/api/Traceability/CreateProducts", form)
      .then((res) => {
        if (res.data.code == 100) {
          ElMessage.success(res.data.msg);
          getProductsShoop();
          dialog.dialogFormVisible = false;
          return;
        } else {
          if (res.data.code == 301) {
            console.log(res.data.msg);
            ElMessage.error(res.data.msg);
            return;
          } else {
            ElMessage.error("添加失败");
            return;
          }
        }
      });
  } else {
    axios
      .put("http://localhost:5004/api/Traceability/UpdataProducts", form)
      .then((res) => {
        console.log(res);
        if (res.data.code == 206) {
          ElMessage.success(res.data.msg);

          getProductsShoop();
          dialog.dialogFormVisible = false;
          return;
        } else {
          ElMessage.success(res.data.msg);
          return;
        }
      });
  }
};

const open = (row: any) => {
  if (row == null) {
    dialog.dialogFormVisible = true;
    dialog.title = "添加页面";
    dialog.IsAdd = true;
    (form.productsId = 0),
      (form.shoopId = 0),
      (form.batchId = 0),
      (form.shelflife = 0),
      (form.productionnumber = ""),
      (form.manufacturers = ""),
      (form.productsimg = ""),
      (form.createName = store.ccstore.userName),
      (form.createTime = new Date()),
      (form.isDel = true);
  } else {
    dialog.dialogFormVisible = true;
    dialog.title = "修改页面";
    dialog.IsAdd = false;
    (form.productsId = row.productsId),
      (form.shoopId = row.shoopId),
      (form.batchId = row.batchId),
      (form.shelflife = row.shelflife),
      (form.productionnumber = row.productionnumber),
      (form.manufacturers = row.manufacturers),
      (form.productsimg = row.productsimg),
      (form.updateName = store.ccstore.userName),
      (form.updateTime = new Date()),
      (form.isDel = row.isDel);
  }
};

// 删除

const DelProducts = (productsId: number) => {
  axios
    .put("https://localhost:7238/api/Traceability/DelProducts/DelProducts", {
      productsId: productsId,
    })
    .then((res) => {
      if (res.data.code == 204) {
        ElMessage.success(res.data.msg);
        return;
      } else {
        ElMessage.error("删除失败");
        return;
      }
    });
};

// 批删
const selectable = (row: any) => ![1, 2].includes(row.id);
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
  // console.log(multipleSelection.value)/*  */
};

// 批量删除
const BatchBut = () => {
  var ids = <any>[];
  multipleSelection.value.forEach((item) => {
    ids.push(item.productsId);
  });
  console.log(ids);
  axios
    .put("https://localhost:7238/api/Traceability/DatchDel", {
      productsId: ids,
    })
    .then((res) => {
      if (res.data.code == 204) {
        ElMessage.success(res.data.msg);
        return;
      } else {
        ElMessage.error("批量删除失败");
        return;
      }
    });
};


// 跳转养殖信息页面
const getFarmsInfo = (batchId: number) => {
  alert(batchId);
  router.push({
    path: "/FarmsInfoView",
    query: {
      BatchId: batchId,
    },
  })
}
//#endregion
</script>

<style scoped>
</style>